<!-- 进货 -->
<template>
  <div>
    <el-row class="mt10" type="flex">
      <Search :data="selections" :attribute="'createdTime'" @dateChange="handleDateChange" @change="handleTypeChange" />
      <el-form ref="searchFormRef" :model="searchForm" label-width="100px" :inline="true">
        <!--        <el-select v-model="searchForm.type" placeholder="请选择操作方式" @change="typeChange">-->
        <!--          <el-option v-for="item in operatingMode" :key="item.id" :label="item.name" :value="item.id" />-->
        <!--        </el-select>-->
        <!--        <el-form-item>-->
        <!--          <el-button type="primary" @click="stockButton">进货</el-button>-->
        <!--        </el-form-item>-->
      </el-form>
    </el-row>
    <!-- 表单区域 -->
    <el-table v-loading="loading" :data="stockList">
      <el-table-column label="进货单号" prop="dataCode" />
      <el-table-column label="时间" prop="handDate" />
      <el-table-column label="操作人" prop="handler" align="center" />
      <el-table-column label="金额" prop="totalPrice" align="center" />
      <el-table-column label="操作" min-width="120" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="detailsBtn(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page-num="params.page" :page-size="params.pageSize" :on-change="handlePaginationChange" :total="total" />
    <!--进货详情-->
    <Dialog :title="title" :width="80" :visible.sync="detailsVisible" :reveal="false" :loading="detailsLoading" @close="handleClose">
      <div class="headStyle">
        <span>进货单号：{{ stockData.dataCode }}</span>
        <span>操作人员：{{ stockData.handler }}</span>
        <span>操作时间：{{ stockData.handDate }}</span>
      </div>
      <el-table v-loading="loading" :data="stockDetails">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="规格" prop="spec" />
        <el-table-column label="仓库" prop="warehouseName" />
        <el-table-column label="供货商" prop="inventorySupplier" />
        <el-table-column label="批次号" prop="inventoryBatch" />
        <el-table-column label="生产日期" prop="productionDate" />
        <el-table-column label="保质期（天）" prop="expiredTime" />
        <el-table-column label="单位" prop="unit" />
        <el-table-column label="数量" prop="purchaseCount" />
        <el-table-column label="单价" prop="price" />
        <el-table-column label="金额" prop="totalPrice" />
      </el-table>
      <span>
        <span><strong>备注：</strong></span>
        <span>{{ stockData.remark }}</span>
      </span>
    </Dialog>
    <!-- 进货 -->
    <Dialog :title="title" :width="80" :visible.sync="visible" button-text="确定" :loading="loading" @close="handleClose" @confirm="submitStockForm">
      <p>
        <el-button type="primary" style="width: 25%" @click="addDrugBtn">导入货物</el-button>
      </p>
      <el-table v-loading="loading" :data="goodsList">
        <el-table-column label="名称" prop="name" />
        <el-table-column label="规格" prop="spec" min-width="50px" />
        <el-table-column label="售价" prop="sellPrice" min-width="50px" />
        <el-table-column label="仓库" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.warehouseId" placeholder="请选择">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="批次号" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.inventoryBatch" controls-position="right" style="width: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="进货单价" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" controls-position="right" style="width: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="数量" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.purchaseCount" controls-position="right" :min="0" style="width: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" min-width="50px" />
        <el-table-column label="生产日期">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.productionDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :picker-options="pickerOptions" placeholder="选择日期" />
          </template>
        </el-table-column>
        <el-table-column label="保质期（天）" min-width="100px" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.expiredTime" controls-position="right" :min="0" style="width: 80px;" />
          </template>
        </el-table-column>
        <el-table-column label="供货商" min-width="150px" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.inventorySupplier" controls-position="right" style="width: 150px;" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteBtn(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-form ref="requestFromRef" :model="stockInfo">
        <el-form-item>
          <span>
            <span><strong>备注：</strong></span>
            <el-input v-model="stockInfo.remark" type="textarea" :autosize="{ minRows:4}" placeholder="请输入内容" class="textareaCss" />
          </span>
        </el-form-item>
      </el-form>
    </Dialog>
    <Dialog :title="title" :visible.sync="goodsVisible" :loading="goodsLoading" :button-text="buttonName" @close="handleClose" @confirm="submitGoodsForm">
      <el-container>
        <el-aside width="195x">
          <LeftClassification @classificationClist="getClassificationId" />
        </el-aside>
        <el-main>
          <span>
            <el-input v-model="searchParams.name" placeholder="请输入名称或者拼音码" clearable style="width: 200px" />
            <el-button type="primary" :loading="searchLoading" @click="searchGoods">搜索</el-button>
          </span>
          <el-table v-loading="loading" :data="addGoodsList" @selection-change="selectionChange">
            <el-table-column label="名称" prop="name" />
            <el-table-column label="规格" prop="spec" />
            <el-table-column label="单位" prop="unit" />
            <el-table-column label="描述" prop="remarks" />
            <el-table-column type="selection" />
          </el-table>
          <pagination :page-num="searchParams.page" :page-size="searchParams.pageSize" :on-change="addGoodsChange" :total="searchTotal" />
        </el-main>
      </el-container>
    </Dialog>
  </div>
</template>
<script>
import Dialog from "@/components/Dialog/index";
import LeftClassification from "../../../components/leftClassification";
import { selections } from "@/config";
import Search from "@/components/Search";
export default {
  components: {
    Dialog,
    LeftClassification,
    Search,
  },
  data() {
    return {
      selections,
      searchForm: {},
      stockInfo: {},
      searchParams: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      params: {
        page: 1,
        pageSize: this.$store.state.commonsettings.maxPageSize,
      },
      total: 0,
      searchTotal: 0,
      options: [],
      stockList: [],
      stockListData: {},
      goodsList: [],
      selectGoods: [],
      addGoodsList: [],
      warehouseList: [],
      buttonName: '',
      stockDetails: [],
      stockData: [],
      title: "",
      visible: false,
      goodsVisible: false,
      detailsVisible: false,
      loading: false,
      goodsLoading: false,
      searchLoading: false,
      detailsLoading: false,
      operatingMode: [
        {
          id: 1,
          name: "进货记录",
        },
        {
          id: 2,
          name: "出货记录",
        },
      ],
      search: {},
      pickerOptions: {
        disabledDate(time) { // 禁用选择之前的日期
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // rules: {
      //   warehouseId: [
      //     { required: true, message: '请选择仓库', trigger: 'change' },
      //   ],
      //   inventoryBatch: [
      //     { required: true, message: '请输入批次', trigger: 'change' },
      //   ],
      //   price: [
      //     { required: true, message: '请输入单价', trigger: 'change', type: Number },
      //   ],
      //   productionDate: [
      //     { required: true, message: '请输入生产日期', trigger: 'change' },
      //   ],
      //   expiredTime: [
      //     { required: true, message: '请输入保质期', trigger: 'change' },
      //   ],
      // },
    };
  },
  created() {
    this.getStockList();
    this.findAllWarehouse();
  },
  methods: {
    async getStockList() {
      this.loading = true;
      const res = await this.$api['warehouse/stock/stockList']({ ...this.params, query: this.search });
      this.loading = false;
      if (res.code !== 200) return this.$message.error('查询进货列表失败！');
      this.stockList = res.data.result;
      this.total = res.data.total;
    },
    handlePaginationChange(val) {
      this.params = { page: val.pageNum, pageSize: val.pageSize };
      this.getStockList();
    },
    addGoodsChange(val) {
      this.searchParams = { page: val.pageNum, pageSize: val.pageSize };
      this.searchGoods();
    },
    // 详情
    async detailsBtn(row) {
      this.detailsLoading = true;
      const pamars = {
        dataCode: row.dataCode,
      };
      const res = await this.$api['warehouse/stock/stockDetails']({ query: pamars });
      if (res.code === 200 && res.data) {
        this.stockData = row;
        this.stockDetails = res.data.result;
      } else {
        this.stockData = {};
        this.stockDetails = [];
      }
      this.title = "进货详情";
      this.detailsVisible = true;
      this.detailsLoading = false;
    },
    // 进货
    stockButton() {
      this.title = "进货";
      this.goodsList = [];
      this.loading = true;
      this.visible = true;
      this.loading = false;
    },
    // 导入货物
    addDrugBtn() {
      this.title = "选择货物";
      this.buttonName = "已选择（0）";
      this.goodsLoading = true;
      this.searchGoods();
      this.goodsVisible = true;
      this.goodsLoading = false;
    },
    // 删除货物
    async deleteBtn(row) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      }
      for (var i = 0; i < this.goodsList.length; i++) {
        if (this.goodsList[i].id === row.id) {
          this.goodsList.splice(i, 1);
        }
      }
      this.$message.success('删除货品成功！');
    },
    // 搜索商品
    async searchGoods() {
      this.searchLoading = true;
      const res = await this.$api['warehouse/stock/goodsList']({ query: this.searchParams });
      this.searchLoading = false;
      if (res.code !== 200) return this.$message.error('查询货品列表失败！');
      this.addGoodsList = res.data.result;
      this.searchTotal = res.data.total;
    },
    // 选择商品
    selectionChange(val) {
      this.buttonName = "已选择（" + val.length + "）";
      this.selectGoods = val;
    },
    // 提交商品表单
    submitGoodsForm() {
      console.log("提交表单");
      // 先删除重复的货物
      for (var i = 0; i < this.goodsList.length; i++) {
        for (var j = 0; j < this.selectGoods.length; j++) {
          if (this.goodsList[i].id === this.selectGoods[j].id) {
            this.selectGoods.splice(j, 1);
          }
        }
      }
      this.goodsList.push(...this.selectGoods);
      this.goodsList.filter(item => {
        item.materialMedicineId = item.id;
        item.inventoryProducer = item.producerName;
      });
      console.log(this.goodsList);
      this.selectGoods = [];
      this.goodsVisible = false;
    },
    // 提交进货表单
    async submitStockForm() {
      console.log("提交进货表单");
      // 添加仓库名称
      for (var i = 0; i < this.goodsList.length; i++) {
        for (var j = 0; j < this.warehouseList.length; j++) {
          if (this.goodsList[i].warehouseId === this.warehouseList[j].id) {
            this.goodsList[i].warehouseName = this.warehouseList[j].name;
          }
        }
      }
      this.stockInfo.handler = this.$store.getters.currentUserInfo.name;
      if (this.goodsList.length === 0) return this.$message.error('进货商品不能为空！');
      console.log("this.goodsList", this.goodsList);
      this.loading = true;
      const res = await this.$api['warehouse/stock/stock']({ purchaseOrderDtoList: this.goodsList, ...this.stockInfo });
      this.loading = false;
      this.visible = false;
      this.goodsList = [];
      this.stockInfo = {};
      if (res.code !== 200) return this.$message.error('添加进货失败！');
      this.$message.success('添加进货成功！');
      this.getStockList();
    },
    // 获取库房列表
    async findAllWarehouse() {
      this.loading = true;
      const res = await this.$api['warehouse/stock/allWarehouse']();
      this.loading = false;
      if (res.code !== 200) return this.$message.error('获取仓库列表失败！');
      this.warehouseList = res.data;
    },
    // 获取产品分类id
    async getClassificationId(val) {
      console.log(val);
      // 查询提交的产品分类id
      this.searchParams.productClassificationId = val.list.join(",");
      const res = await this.$api['warehouse/stock/goodsList']({ query: this.searchParams });
      if (res.code !== 200) return this.$message.error('查询货品列表失败！');
      this.addGoodsList = res.data.result;
      this.searchTotal = res.data.total;
    },
    // async typeChange(val) {
    //   // if (val) {
    //   //   this.params.inventoryType = val;
    //   // } else {
    //   //   this.params.inventoryType = undefined;
    //   // }
    //   Object.assign(this.search, val);
    //   this.getStockList();
    // },
    // 关闭
    handleClose() {
      this.searchLoading = false;
      this.loading = false;
      this.goodsLoading = false;
      // this.$refs.ruleForm.resetFields();
    },
    handleDateChange(val) {
      Object.assign(this.search, val);
      this.getStockList();
    },
    handleTypeChange(val) {
      Object.assign(this.search, val);
      this.getStockList();
    },
  },
};
</script>
<style lang="scss" scoped>
.headStyle.fofo {
  padding-top: 15px;
  margin-top: 15px;
  border-top: 1px dashed #eee !important;
}
.el-steps {
  justify-content: center;
}
.el-aside {
  background: #fff;
}
</style>

